import store from "../store";
import service from "../common/service";
import dateRangUtil from "../common/dateRangUtil"
import { useMainStore } from "@/store/modules/store";
import Guid from "../common/guid";

/**
 * @description 获取最新的 EnjoyBCM 值
 * @returns {string} EnjoyBCM
 */
const getEnjoyBCM = () => {
  const mainStore = useMainStore();
  const enjoyServiceIp = mainStore.enjoyServiceIp;
  const EnjoyBCM = enjoyServiceIp?.EnjoyBCM?.split('/Enjoy/Service')[0] || '';
  return EnjoyBCM;
};

/**
 * @description 获取最新的 EnjoyOA 值
 * @returns {string} EnjoyOA
 */
const getEnjoyOA = () => {
  const mainStore = useMainStore();
  const enjoyServiceIp = mainStore.enjoyServiceIp;
  const EnjoyOA = enjoyServiceIp?.EnjoyOA?.split('/Enjoy/Service')[0] || '';
  return EnjoyOA;
};

const getEnjoyMbmMain = () => {
  const mainStore = useMainStore();
  const enjoyServiceIp = mainStore.enjoyServiceIp;
  const EnjoyMBMMain = enjoyServiceIp?.EnjoyMain?.split('/Enjoy/Service')[0] || '';
  return EnjoyMBMMain;
};

/**
 * @description 获取最新的 bcmUrl
 * @returns {object} bcmUrl
 */
const getBcmUrl = () => {
  const EnjoyBCM = getEnjoyBCM();
  const EnjoyOA = getEnjoyOA();
  
  //管e通的服务
  const EnjoyMBMMain = getEnjoyMbmMain();
  return {
    mainApi: `${EnjoyOA}/main/api/Enjoy/Service`,//后台框架服务、后台OA服务
    adminApi: `${EnjoyBCM}/bcm/admin/api/Enjoy/Service`,
    orderApi: `${EnjoyBCM}/bcm/order/api/Enjoy/Service`,
    stockApi: `${EnjoyBCM}/bcm/stock/api/Enjoy/Service`,
    managerApi: `${EnjoyBCM}/bcm/manager/api/Enjoy/Service`,
	  mbmApi: `${EnjoyMBMMain}/Enjoy/Service`,//管e通的服务
    wsApi: `${EnjoyBCM}/bcm/manager/webSocket`
  };
};

/**
 * @description bcm请求
 * @param {string} url 请求地址
 * @param {string} uniqueKey 唯一标识
 * @param {string} methodName 方法名
 * @param {object} objectData 请求参数
 * @param {string} billType 单据类型
 * @returns {Promise} Promise
 */
const bcmRequest = async (url="", uniqueKey="", methodName="", objectData:any=undefined, billType = '' ) => {
  const Tag = Guid.NewGuid().ToString();
  return new Promise((resolve, reject) => {
    let request = {
      url,
      data: {
        UniqueKey: uniqueKey,
        MethodName: methodName,
        ObjectData: objectData,
        BillType: billType,
        Tag
      },
    };
    service.request(request, (res:any) => {
      if (res && res.data) {
        if (!res.data.HasException) {
          resolve(res.data.ObjectData);
        } else {
          uni.showToast({
            duration: 3500,
            icon: 'none',
            title: res.data.Exception.Message,
            mask: true,
          });
          reject(res.data.Exception.Message);
        }
      }
    }, () => {
      console.log('请求失败');
      reject('请求失败');
    });
  });
};


/**
 * @description bcm请求
 * @param {string} url 请求地址
 * @param {string} uniqueKey 唯一标识
 * @param {string} methodName 方法名
 * @param {object} objectData 请求参数
 * @param {string} billType 单据类型
 * @returns {Promise} Promise
 */
const bcmRequestAsync = async (url="", uniqueKey="", methodName="", objectData=undefined, billType = '') => {
  const Tag = Guid.NewGuid().ToString();
    return new Promise((resolve, reject) => {
      let request = {
        url,
        data: {
          UniqueKey: uniqueKey,
          MethodName: methodName,
          ObjectData: objectData,
          BillType: billType,
          Tag
        },
      };
      service.request(request, (res:any) => {
        if (res && res.data) {
            resolve(res.data);
        }
      }, () => {
        console.log('请求失败');
        reject('请求失败');
      });
    });
  };


  const refreshToken = async () => {
    const bcmUrl = getBcmUrl()
    const EXPIRES = 1000 * 60 * 2; // 提前失效前2分钟刷新
    const mainStore = useMainStore();
    const { sUser, dServerDt, idsToken } = mainStore.loginInfo
    const { expires_in, refresh_token } = idsToken; // 令牌的有效期（以秒为单位）
    // 计算令牌的过期时间
    let tokenExpirationTime = new Date(dServerDt).getTime() + (expires_in*1000);
    // 获取当前时间
    let now = new Date().getTime();
    let isExpires = tokenExpirationTime <= now + EXPIRES;
    // console.log("---------refreshToken---------", expires_in, refresh_token, sUser, dServerDt, isExpires )
    // 判断令牌是否过期
    if (isExpires) {
      // token 即将失效，更新token
      // console.log("Token is expired");
      let req = {
        sRefreshToken: refresh_token,
        userNo: sUser,
      }
      // console.log('--------store.state.loginInfo---------: ', store.state.loginInfo)
      service.enjoyShowLoading('正在刷新Token...');
      const tokenResult = await bcmRequest(bcmUrl.mbmApi, '管易通40公共', 'RefreshCenterToken', req);
      // if (tokenResult  && tokenResult.refresh_token ) {
      //   store.commit('loginInfoin', {
      //     ...store.state.loginInfo,
      //     dServerDt: dateRangUtil.formatDate(),
      //     idsToken: tokenResult
      //   })
      // }
      service.enjoyHideLoading();
    } else {
      // token 失效时间大于2分钟
      // console.log("Token is not expired");
    }
  }

export {
  getBcmUrl,
  bcmRequest,
  bcmRequestAsync,
  refreshToken,
  getEnjoyOA,
  getEnjoyBCM,
};